package com.demo.simpletestapp.webview

import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import android.view.View
import android.webkit.*
import android.widget.Toast
import androidx.core.net.toFile
import com.demo.simpletestapp.R
import com.demo.simpletestapp.databinding.ActivityWebViewTestBinding
import com.example.base_lib.BaseActivity
import org.json.JSONObject
import java.io.File


class WebViewTestActivity : BaseActivity<ActivityWebViewTestBinding>() {

    private val url = "https://h5.cadothy.com#/reslib?token=c2a834759f964673b5b8b5f024df87e4&env=release&snCode=0163232430470&versionCode=3804&versionName=4.2.0&language=zh&width=1044&height=1650"

    override fun getLayoutId(): Int {
        return R.layout.activity_web_view_test
    }

    override fun onInit() {
        // 启用JavaScript
        val webSettings: WebSettings = binding.webview.settings
        webSettings.apply {
//是否允许在 WebView 中运行 JavaScript。
            javaScriptEnabled = true
            cacheMode = WebSettings.LOAD_NO_CACHE
//是否启用 DOM 存储功能，允许网页使用 localStorage 和 sessionStorage 存储数据
            domStorageEnabled = true
            //是否支持缩放
            setSupportZoom(true)
            //是否允许通过 JavaScript 打开新窗口。
            javaScriptCanOpenWindowsAutomatically = true

////是否允许定位功能，允许网页获取用户的地理位置信息
//            setGeolocationEnabled(true)
////是否显示内置的缩放控件。
//            builtInZoomControls = true
////是否显示内置缩放控件。
//            displayZoomControls = true
////是否允许 WebView 访问文件系统。
//            allowFileAccess = true
////是否允许 WebView 访问内容提供程序。
//            allowContentAccess = true
////是否自动加载图片。
//            loadsImagesAutomatically = true
////            是否阻止网络图片加载。
//            blockNetworkImage = true
////            是否允许从 file 协议访问内容。
//            allowFileAccessFromFileURLs = true
        }
//        webView.getSettings().setDomStorageEnabled(true);
        // 加载百度网页
        binding.webview.loadUrl(url)
//        binding.webview.loadUrl("https://advisor.myscrm.cn/aconsultant-cms/hkbApp/openLiveLockIn")
//        binding.webview.loadUrl("https://h5.cadothy.com#/download-materials?token=1c6007bce88b45279c7538c95e2a3e47&env=release&snCode=0163232430470&versionCode=3765&versionName=4.2.0&language=zh")

        binding.webview.webViewClient = object:WebViewClient(){
            override fun onRenderProcessGone(
                view: WebView?,
                detail: RenderProcessGoneDetail?
            ): Boolean {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    // Handle the crash here
                    detail?.let {
                        if (it.didCrash()) {
                            Log.e(TAG, "Render process crashed!");
                        } else {
                            Log.e(TAG, "Render process was killed by the system.");
                        }
                        // You can restart the WebView or provide other actions
                        binding.webview.reload();
                    }

                    return true; // Indicate that we handled the crash
                }
                return super.onRenderProcessGone(view, detail)
            }
        }
        // 使用示例
        val webViewVersion = getWebViewVersion()
        println("WebView 内核版本：$webViewVersion")
        binding.webview.addJavascriptInterface(JsInteraction(),"android")
    }

    fun getWebViewVersion(): String {
        // 获取 WebView 的 UserAgent
        val userAgent = binding.webview.settings.userAgentString
        // 使用 UserAgent 提取内核版本信息
        val coreVersion = extractCoreVersionFromUserAgent(userAgent)
        // 返回内核版本信息
        return coreVersion
    }

    fun extractCoreVersionFromUserAgent(userAgent: String): String {
        // 在 UserAgent 中找到包含内核版本信息的关键字，通常是 "Chrome/" 或 "Version/"
        val coreVersionKeyword = if (userAgent.contains("Chrome/")) "Chrome/" else "Version/"
        // 提取内核版本信息
        val startIndex = userAgent.indexOf(coreVersionKeyword) + coreVersionKeyword.length
        val endIndex = userAgent.indexOf(" ", startIndex)
        return if (endIndex > startIndex) {
            userAgent.substring(startIndex, endIndex)
        } else {
            userAgent.substring(startIndex)
        }
    }

    inner class JsInteraction {
        /**
         * 通用下载
         */
        @JavascriptInterface
        fun generalDownload(id: String, url: String, name: String, type: Int) {
        Toast.makeText(this@WebViewTestActivity,"generalDownload",Toast.LENGTH_SHORT).show()
        }

        @JavascriptInterface
        fun updateToken() {
            Toast.makeText(this@WebViewTestActivity,"updateToken",Toast.LENGTH_SHORT).show()
        }

        @JavascriptInterface
        fun changeTab(tabName: String) {
            Toast.makeText(this@WebViewTestActivity,"changeTab",Toast.LENGTH_SHORT).show()
        }

        @JavascriptInterface
        fun changeIndustryType(industryLevel: Int, TypeName: String) {
            Toast.makeText(this@WebViewTestActivity,"changeIndustryType",Toast.LENGTH_SHORT).show()
        }

        @JavascriptInterface
        fun closeWebView() {
            Toast.makeText(this@WebViewTestActivity,"closeWebView",Toast.LENGTH_SHORT).show()
            finish()
        }


        /**
         * 根据不同的类型下载到不同的目录
         */
        private fun typeForDownloadPath(type: Int): String {
            var path = Environment.getExternalStorageDirectory().path + "/"
            when (type) {
                1 -> {//背景图片
                    path += Environment.DIRECTORY_PICTURES + "/" + "背景图片"
                }

                2 -> {//贴图
                    path += Environment.DIRECTORY_PICTURES + "/" + "贴图"
                }

                3 -> {//绿幕元素
                    path += Environment.DIRECTORY_PICTURES + "/" + "绿幕"
                }

                4 -> {//视频
                    path += Environment.DIRECTORY_PICTURES + "/" + "视频"
                }

                5 -> {//音乐
                    path += Environment.DIRECTORY_MUSIC + "/" + "音乐"
                }

                6 -> {//音效
                    path += Environment.DIRECTORY_MUSIC + "/" + "音效"
                }

                7 -> {//文稿
                    path += "文稿"
                }
                else -> {
                    path += Environment.DIRECTORY_PICTURES + "/" + "背景图片"
                }

            }
            if (isExistDir(path)) return path
            else return path + Environment.DIRECTORY_PICTURES

        }

        /**
         * 是否存在目录，如果不存在就创建
         */
        private fun isExistDir(path: String): Boolean {
            var file = File(path)
            if (file.exists()) return true
            else return file.mkdirs()

        }
    }
}